#include <cjson/cJSON.h>
#include <assert.h>

#include "../util.h"
#include "logout.h"

action_logout_result action_logout(
    const char* bind_interface,
    const char* portal_host,
    const char* portal_search,
    const char* user_index
) {
    assert(portal_host != NULL);
    
    action_logout_result result = {
        ACTION_LOGOUT_SUCCESSFULLY,
        NULL
    };
    
    const char* addr_strs[] = {
        "http://",
        portal_host,
        "/eportal/InterFace.do?method=logout",
        NULL
    };
    char* address = string_concat(addr_strs);
    
    const char* post_strs[] = {
        "userIndex=",
        user_index == NULL ? "" : url_encode_component(user_index),
        NULL
    };
    char* post_string = string_concat(post_strs);
    if (user_index != NULL) {
        free((char*) post_strs[1]);
    }
    
    CURL_EASY_SETUP({
        // setup action
        curl_easy_setopt(curl, CURLOPT_COPYPOSTFIELDS, post_string);
        curl_common_setup(curl, portal_host, portal_search);
        free(post_string);
    }, {
        const cJSON* logout = cJSON_Parse(chunk.memory);
        if (logout == NULL) {
            goto failure;
        }
        
        const cJSON* return_status;
        const cJSON* message;
        const cJSON* user_index;
        
        return_status = cJSON_GetObjectItemCaseSensitive(logout, "result");
        if (cJSON_IsString(return_status) && (return_status -> valuestring != NULL)) {
            if (strcmp(return_status -> valuestring, "success") == 0) {
                result.status = ACTION_LOGOUT_SUCCESSFULLY;
            } else if (strcmp(return_status -> valuestring, "fail") == 0) {
                result.status = ACTION_LOGOUT_FAILED;
            } else {
                goto failure;
            } 
        } else {
            goto failure;
        }
        
        message = cJSON_GetObjectItemCaseSensitive(logout, "message");
        if (cJSON_IsString(message) && (message -> valuestring != NULL)) {
            result.message = string_duplicate(message -> valuestring);
        } else {
            goto failure;
        }
        
        if (result.status != ACTION_LOGOUT_SUCCESSFULLY) {
            goto end;
        }
        
        end:
        cJSON_free((cJSON*) logout);
        free(address);
        return result;
        
        failure:
        result.status = ACTION_LOGOUT_PARSING_FAILED;
        goto end;
    }, {
        // failure action
        result.status = ACTION_FETCHING_FAILED;
        free(address);
        return result;
    }, address, bind_interface, 2048);
}
